package com.yxdj.auth.service;

import com.yxdj.common.core.constant.CacheConstants;
import com.yxdj.common.core.constant.Constants;
import com.yxdj.common.core.constant.SecurityConstants;
import com.yxdj.common.core.domain.R;
import com.yxdj.common.core.enums.UserStatus;
import com.yxdj.common.core.exception.ServiceException;
import com.yxdj.common.core.text.Convert;
import com.yxdj.common.core.utils.StringUtils;
import com.yxdj.common.core.utils.ip.IpUtils;
import com.yxdj.common.redis.service.RedisService;
import com.yxdj.system.api.domain.SysUser;
import com.yxdj.system.api.model.LoginUser;
import com.yxdj.user.api.RemoteEngineerService;
import com.yxdj.user.api.domain.Engineer;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class AppEngineerService
{
    @Autowired
    private RemoteEngineerService remoteEngineerService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     */
    public LoginUser login(String phone, String code)
    {
        // 手机号或验证码为空 错误
        if (StringUtils.isAnyBlank(phone, code))
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "手机号/验证码必须填写");
            throw new ServiceException("手机号/验证码必须填写");
        }

        // 手机号不在指定范围内 错误
        if (phone.length() != 11)
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "请输入11位的手机号码");
            throw new ServiceException("请输入11位的手机号");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }

        //获取Redis中的验证码
        String redisCode = redisService.getCacheObject("app:user:" + phone);
        //验证验证码是否正确
        if(!code.equals(redisCode)){
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "验证码错误");
            throw new ServiceException("验证码错误");
        }

        //删除Redis中的验证码
        redisService.deleteObject("app:user:" + phone);

        // 查询用户信息
        R<Engineer> engineerResult = remoteEngineerService.login(phone, SecurityConstants.INNER);

        if (R.FAIL == engineerResult.getCode())
        {
            throw new ServiceException(engineerResult.getMsg());
        }

        Engineer engineer = engineerResult.getData();

        if (null == engineer)
        {
            //注册新用户
            engineer = new Engineer();
            engineer.setPhoneNumber(phone);
            engineer.setAvatarUrl("https://mty-house.oss-cn-beijing.aliyuncs.com/avatarurl/logo.png");
            engineer.setEmployeeId("MTY_"+ RandomStringUtils.randomNumeric(4));
            //插入新用户
            R<Engineer> register = remoteEngineerService.register(engineer, SecurityConstants.INNER);
            if (R.FAIL == register.getCode())
            {
                throw new ServiceException(register.getMsg());
            }
            engineer = register.getData();
        }

        if (UserStatus.DISABLE.getCode().equals(engineer.getStatus()))
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + phone + " 已停用");
        }

        recordLogService.recordLogininfor(phone, Constants.LOGIN_SUCCESS, "登录成功");

        //创建LoginUser对象
        LoginUser loginUser = new LoginUser();
        SysUser sysUser = new SysUser();
        //创建token需要用户id和用户名
        sysUser.setUserId(engineer.getId());
        sysUser.setUserName(engineer.getPhoneNumber());
        sysUser.setAvatar(engineer.getAvatarUrl());
        sysUser.setNickName(engineer.getName() != null?engineer.getName():engineer.getEmployeeId());
        loginUser.setSysUser(sysUser);

        return loginUser;
    }


    public void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

}
